import Flutter
import CoreBluetooth
import UIKit

public class PermissionPlugin: NSObject, FlutterPlugin {
    
    var channel: FlutterMethodChannel
    var centralManager: CBCentralManager!
    
    init(channel: FlutterMethodChannel) {
        self.channel = channel
        super.init()
        self.centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "permission", binaryMessenger: registrar.messenger())
    let instance = PermissionPlugin(channel: channel)
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "getPlatformVersion":
      result("iOS " + UIDevice.current.systemVersion)
    default:
      result(FlutterMethodNotImplemented)
    }
  }
}

extension PermissionPlugin: CBCentralManagerDelegate{
    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .unknown, .resetting, .unsupported, .unauthorized, .poweredOff:
            self.channel.invokeMethod("onAdapterStateChanged", arguments: false)
            break
        case .poweredOn:
            self.channel.invokeMethod("onAdapterStateChanged", arguments: true)
            break
        }
    }
    
    
}
